// DOM 元素
const fileInput = document.getElementById('fileInput');
const chunkSizeInput = document.getElementById('chunkSize');
const processBtn = document.getElementById('processBtn');
const resultDiv = document.getElementById('result');
const downloadAllDiv = document.getElementById('downloadAll');
const downloadAllBtn = document.getElementById('downloadAllBtn');
const logDiv = document.getElementById('log');
const qrNavigationDiv = document.getElementById('qrNavigation');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
const pageInfo = document.getElementById('pageInfo');
const qrSizeSelect = document.getElementById('qrSizeSelect');

// 状态
let chunks = [];
let qrCanvases = [];
let currentPage = 0;
let qrSize = 200;

// 文件选择后启用按钮
fileInput.addEventListener('change', () => {
    processBtn.disabled = !fileInput.files.length;
});

// CRC32 计算函数
function calculateCRC32(data) {
    const table = [];
    for (let i = 0; i < 256; i++) {
        let c = i;
        for (let j = 0; j < 8; j++) {
            c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
        }
        table[i] = c;
    }
    
    let crc = 0 ^ (-1);
    for (let i = 0; i < data.length; i++) {
        crc = (crc >>> 8) ^ table[(crc ^ data[i]) & 0xFF];
    }
    return (crc ^ (-1)) >>> 0;
}

// 主处理函数
processBtn.addEventListener('click', async () => {
    const file = fileInput.files[0];
    if (!file) return;

    const chunkSize = parseInt(chunkSizeInput.value) || 500;
    log(`⚙️ 开始处理文件：${file.name}，分块大小：${chunkSize}`);

    try {
        // 读取文件为 ArrayBuffer
        const arrayBuffer = await file.arrayBuffer();
        const uint8Array = new Uint8Array(arrayBuffer);

        // 计算原始文件的CRC32校验码
        const originalCRC32 = calculateCRC32(uint8Array);
        log(`🔐 原始文件CRC32校验码：${originalCRC32.toString(16).toUpperCase()}`);

        // 压缩
        const compressed = pako.deflate(uint8Array);
        log(`📦 压缩完成，原大小：${uint8Array.length} → 压缩后：${compressed.length}`);

        // Base64 编码
        let binary = '';
        for (let i = 0; i < compressed.length; i++) {
            binary += String.fromCharCode(compressed[i]);
        }
        const base64 = btoa(binary);
        log(`🔠 Base64 编码完成，长度：${base64.length}`);

        // 准备文件元数据
        const fileMetadata = {
            name: file.name,
            type: file.type || 'application/octet-stream',
            size: file.size,
            crc32: originalCRC32.toString(16).toUpperCase()
        };
        const metadataStr = JSON.stringify(fileMetadata);
        const metadataBase64 = btoa(unescape(encodeURIComponent(metadataStr)));
        log(`📋 文件元数据：${file.name} (${file.size} bytes, ${file.type})`);

        // 分块（为元数据预留空间）
        const adjustedChunkSize = chunkSize - metadataBase64.length - 10; // 预留分隔符空间
        chunks = [];
        for (let i = 0; i < base64.length; i += adjustedChunkSize) {
            chunks.push(base64.substring(i, Math.min(i + adjustedChunkSize, base64.length)));
        }
        log(`🧩 分成 ${chunks.length} 个块`);

        // 生成二维码
        resultDiv.innerHTML = '';
        qrCanvases = [];
        currentPage = 0;
        
        for (let i = 0; i < chunks.length; i++) {
            const index = i + 1;
            const total = chunks.length;
            
            // 新格式：序号/总数|元数据|数据块
            const content = `${index}/${total}|${metadataBase64}|${chunks[i]}`;

            const qrItem = document.createElement('div');
            qrItem.className = 'qr-item';
            if (i === 0) qrItem.classList.add('active'); // 默认显示第一个
            // 格式化文件大小
            const formatFileSize = (bytes) => {
                if (bytes === 0) return '0 B';
                const k = 1024;
                const sizes = ['B', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            };
            
            const fileSizeFormatted = formatFileSize(file.size);
            qrItem.innerHTML = `
                <h4>第 ${index} 块（共 ${total} 块）</h4>
                <canvas></canvas>
                <p>文件：${file.name}</p>
                <p>大小：${fileSizeFormatted}</p>
                <p>块大小：${chunks[i].length} 字符</p>
            `;

            const canvas = qrItem.querySelector('canvas');
            qrCanvases.push(canvas);

            resultDiv.appendChild(qrItem);

            // 生成二维码到 canvas
            await new Promise(resolve => {
                QRCode.toCanvas(canvas, content, { width: qrSize, margin: 2 }, error => {
                    if (error) console.error(error);
                    resolve();
                });
            });
        }

        // 显示导航控件
        if (chunks.length > 1) {
            qrNavigationDiv.style.display = 'block';
            updateNavigation();
        }
        
        downloadAllDiv.style.display = 'block';
        log(`✅ 二维码生成完成！包含文件元数据和CRC32校验`);
    } catch (err) {
        log(`❌ 处理失败：${err.message}`);
    }
});

// 批量下载所有二维码
downloadAllBtn.addEventListener('click', () => {
    if (qrCanvases.length === 0) return;

    qrCanvases.forEach((canvas, index) => {
        setTimeout(() => {
            canvas.toBlob(blob => {
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `qr_chunk_${index + 1}.png`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            }, 'image/png');
        }, index * 100); // 避免浏览器并发下载限制
    });

    log(`💾 开始下载 ${qrCanvases.length} 个二维码图片...`);
});

// 导航功能
function updateNavigation() {
    const total = chunks.length;
    prevBtn.disabled = currentPage === 0;
    nextBtn.disabled = currentPage === total - 1;
    pageInfo.textContent = `第 ${currentPage + 1} 页，共 ${total} 页`;
    
    // 更新显示的二维码
    const qrItems = resultDiv.querySelectorAll('.qr-item');
    qrItems.forEach((item, index) => {
        item.classList.toggle('active', index === currentPage);
    });
}

// 上一页按钮
prevBtn.addEventListener('click', () => {
    if (currentPage > 0) {
        currentPage--;
        updateNavigation();
    }
});

// 下一页按钮
nextBtn.addEventListener('click', () => {
    if (currentPage < chunks.length - 1) {
        currentPage++;
        updateNavigation();
    }
});

// 二维码大小调整
qrSizeSelect.addEventListener('change', async () => {
    qrSize = parseInt(qrSizeSelect.value);
    
    if (qrCanvases.length === 0) return;
    
    log(`🔄 调整二维码大小为 ${qrSize}px...`);
    
    // 重新生成所有二维码 - 需要重新计算CRC32
    const file = fileInput.files[0];
    if (!file) return;
    
    // 重新读取文件并计算CRC32
    const arrayBuffer = await file.arrayBuffer();
    const uint8Array = new Uint8Array(arrayBuffer);
    const originalCRC32 = calculateCRC32(uint8Array);
    
    const fileMetadata = {
        name: file.name,
        type: file.type || 'application/octet-stream',
        size: file.size,
        crc32: originalCRC32.toString(16).toUpperCase()
    };
    const metadataStr = JSON.stringify(fileMetadata);
    const metadataBase64 = btoa(unescape(encodeURIComponent(metadataStr)));
    
    for (let i = 0; i < chunks.length; i++) {
        const index = i + 1;
        const total = chunks.length;
        const content = `${index}/${total}|${metadataBase64}|${chunks[i]}`;
        
        const canvas = qrCanvases[i];
        canvas.width = qrSize;
        canvas.height = qrSize;
        
        await new Promise(resolve => {
            QRCode.toCanvas(canvas, content, { width: qrSize, margin: 2 }, error => {
                if (error) console.error(error);
                resolve();
            });
        });
    }
    
    // 更新CSS样式
    const style = document.createElement('style');
    style.textContent = `.qr-item canvas { width: ${qrSize}px !important; height: ${qrSize}px !important; }`;
    document.head.appendChild(style);
    
    log(`✅ 二维码大小调整完成`);
});

// 键盘导航支持
document.addEventListener('keydown', (e) => {
    if (chunks.length <= 1) return;
    
    if (e.key === 'ArrowLeft' && currentPage > 0) {
        currentPage--;
        updateNavigation();
    } else if (e.key === 'ArrowRight' && currentPage < chunks.length - 1) {
        currentPage++;
        updateNavigation();
    }
});

// 日志函数
function log(message) {
    logDiv.style.display = 'block';
    logDiv.innerHTML += `[${new Date().toLocaleTimeString()}] ${message}<br>`;
    logDiv.scrollTop = logDiv.scrollHeight;
    console.log(message);
}